package com.example.demo.netty;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.*;

public class HelloHandler extends SimpleChannelHandler {

    /**
     * 接受消息
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        System.out.println("messageReceived");
       // Object msg = e.getMessage();
        //StringDecoder 解决
        //ChannelBuffer channelBuffer= (ChannelBuffer) msg;
//        System.out.println(new String(channelBuffer.array()));
        System.out.println(e.getMessage().toString());


        //会写数据给客户端
        Channel channel = ctx.getChannel();

        //返回必须是channelbuffer
        //ChannelBuffer buffer = ChannelBuffers.copiedBuffer("xixi".getBytes());
        channel.write("收到啦");
        super.messageReceived(ctx, e);
    }


    /**
     * 建立新的连接
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelConnected");
        super.channelConnected(ctx, e);
    }


    /**
     * 异常
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        System.out.println("exceptionCaught");
        super.exceptionCaught(ctx, e);
    }


    /**
     * 关闭连接
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelClosed");
        super.channelClosed(ctx, e);
    }
}
